<template>
	<!-- 系统目录 西药目录 -->
	<div class="box" id="rightCont">
		<!-- main -->
		<div class="main" id="main">
			<!-- right -->
			<div class="main-right">
				<div class="main-icon">
					<div class="main-icon-a">
						<i :class="iconComes" style="border-radius: 50%;font-size: 20px;padding: 6px;margin-left: 8px;;background-color: #409EFF;color: #fff;"></i>
						<span style="font-size: 14px;font-weight:300;margin-left: 12px;color: #606266;">{{ CatalogueName }}</span>
					</div>
					<!-- 搜索 -->
					<div class="main-icon-c">
						<span style="font-size: 12px;color: #606266;font-weight: bold;display: inline-block;width: 68px;">关键字：</span>
						<el-autocomplete popper-class="my-autocomplete" v-model="searchValue" :fetch-suggestions="querySearch" placeholder="编码、药品名称"
						  size='mini' @select="handleSelect">
						  <i class="el-icon-Ssearch" slot="suffix" style="cursor: pointer;margin-right: 8px;" @click="handleIconClick"></i>
						  <template slot-scope="{ item }">
							<div class="name" style="font-size: 12px;">{{ item.drugCodeName }}</div>
						  </template>
						</el-autocomplete>
					</div>
					<!-- btn3 -->
					<div class="main-icon-c">
						<el-button v-for="(v,i) in headerBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini" @click="handClick(i)">{{ v.title }}</el-button>
					</div>
				</div>
			
				<!-- table -->
				<div class="table">
					<el-table :data="tableData" border @row-dblclick="handledbRow" :max-height="tableHeight"
					element-loading-text="数据加载中..." v-loading="loading" element-loading-spinner="el-icon-refresh"
					highlight-current-row @current-change="handleCurrentTableChange"
					:row-class-name="tableRowClassName">
						<el-table-column label="系统序号" prop="id" width="88"></el-table-column>
						<el-table-column v-for="(col, inx) in tableRows" :key="inx" :type="col.type" :prop="col.prop" :label="col.name" :width="columnWidth(col, tableData)"></el-table-column>
						<el-table-column prop="basMednB" label="基本药物" width="88">
							 <template slot-scope="{ row }">
								<!-- 根据state显示不同的内容 -->
								<span>{{ TypeMap[row.basMednB] || '' }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="antcB" label="是否抗生素" width="88">
							 <template slot-scope="{ row }">
								<!-- 根据state显示不同的内容 -->
								<span>{{ TypeMap[row.antcB] || '' }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="expensiveType" sortable label="贵重类型" width="99">
							 <template slot-scope="{ row }">
								<!-- 根据state显示不同的内容 -->
								<span>{{ expensiveTypeMap[row.expensiveType] || '' }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="clinicId" sortable label="隶属诊所" width="99">
							 <template slot-scope="{ row }">
								<!-- 根据state显示不同的内容 -->
								<span>{{ docclinicMap[row.clinicId] || '' }}</span>
							</template>
						</el-table-column>
						<el-table-column label="医保名称" prop="chsName" width="128"></el-table-column>
						<el-table-column label="医保编码" prop="chsCode" width="128"></el-table-column>
						<el-table-column label="YPID" prop="ypId" width="128"></el-table-column>
						<el-table-column label="有效状态" prop="status" width="128"></el-table-column>
						<el-table-column label="操作人" prop="createId" width="128"></el-table-column>
						<el-table-column label="操作时间" prop="createTime" width="128"></el-table-column>
						<el-table-column label="备注" prop="remark" width="128"></el-table-column>
						<!-- edit -->
						<!-- <el-table-column fixed="right" label="操作" width="88">
						  <template slot-scope="scope">
							  <div class="editbox" style="text-align: center;">
								<el-button type="text" @click="editFormValue(scope.row)" size="mini">编辑</el-button>
								<el-button type="text" @click="handleDelete(scope.row.id)" size="mini">删除</el-button>
							  </div>
						  </template>
						</el-table-column> -->
						<!-- fixed -->
						<el-table-column fixed="left" label="行号" type="index" width="50" align="center"></el-table-column>
					</el-table>
					<!-- 分页 -->
					<el-pagination
					style="margin: 12px;"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="pageNum"
					:page-sizes="[20, 50, 100]"
					:page-size="pageSize"
					:total="totalSize"
					layout="total, sizes, prev, pager, next, jumper"
					background
					>
					</el-pagination>
				</div>
				<!-- feet -->
				<div class="feet" id="feet">
					<el-button v-for="(v,i) in feetBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini" @click="feetHandClick(v,i)">{{ v.title }}</el-button>
				</div>
			</div>
		</div>
		<div class="excel">
			<!-- Excel导入对话框 -->
			  <el-dialog 
			    title="Excel导入" 
			    :visible.sync="excelDialogVisible" 
			    width="68%"
			    top="5vh"
				:modal="false"
			    custom-class="excel-import-dialog"
			  >
			    <div class="excel-import-container">
			      <!-- 左侧上传区域 -->
			      <div class="left-panel">
			        <!-- 上传头部 -->
			        <div class="upload-header">
			          <el-upload
			            class="upload-demo"
			            drag
			            action=""
			            :auto-upload="false"
			            :file-list="excelFileList"
			            :before-upload="beforeExcelUpload"
			            :on-change="handleExcelChange"
			            accept=".xlsx, .xls"
			          >
			            <i class="el-icon-upload"></i>
			            <div class="el-upload__text">将Excel文件拖到此处，或<em>点击上传</em></div>
			            <div class="el-upload__tip" slot="tip">只能上传xlsx/xls文件，且不超过10MB</div>
			          </el-upload>
			        </div>
			
			        <!-- 文件信息区域 -->
			        <div class="file-info">
			          <div class="file-type-select">
			            <el-form label-width="80px" size="mini">
			              <el-form-item label="文件类型">
			                <el-select v-model="fileType">
			                  <el-option label="Excel" value="excel"></el-option>
			                </el-select>
			              </el-form-item>
			              <el-form-item label="文件路径">
			                <el-input 
			                  v-model="filePath" 
			                  placeholder="上传后自动显示文件路径"
			                  readonly
			                >
			                  <el-button 
			                    slot="append" 
			                    icon="el-icon-refresh"
			                    @click="reSelectFile"
			                    :disabled="!excelFileList.length"
			                  >重新选择</el-button>
			                </el-input>
			              </el-form-item>
			            </el-form>
			          </div>
			
			          <!-- 文件列表表格 -->
			          <div class="file-table">
			            <el-table :data="fileList" border height="188">
			              <el-table-column style="font-size: 12px;" prop="name" label="文件名称" width="180"></el-table-column>
			              <el-table-column style="font-size: 12px;" prop="path" label="文件路径" show-overflow-tooltip></el-table-column>
			              <el-table-column style="font-size: 12px;" prop="status" label="状态" width="100">
			                <template slot-scope="{row}">
			                  <el-tag :type="row.status === '导入成功' ? 'success' : 'danger'" size="mini">
			                    {{row.status}}
			                  </el-tag>
			                </template>
			              </el-table-column>
			              <el-table-column label="操作" width="80" align="center">
			                <template slot-scope="{row}">
			                  <el-button 
			                    type="danger" 
			                    icon="el-icon-del" 
			                    size="mini" 
			                    circle
			                    @click="removeFile(row)"
			                  ></el-button>
			                </template>
			              </el-table-column>
			            </el-table>
			          </div>
			        </div>
			
			        <!-- 底部操作按钮 -->
			        <div class="action-footer">
			          <el-button 
			            type="primary" 
			            size="medium" 
			            @click="submitExcel"
			            :loading="loading"
			            :disabled="!excelTableData.length"
			          >立即执行</el-button>
			        </div>
			      </div>
			
			      <!-- 右侧预览区域 -->
			      <div class="right-panel">
			        <div class="preview-header">
			          <h4>数据预览 (共 {{ excelTableData.length }} 条记录)</h4>
			        </div>
			        
			        <!-- 预览表格 -->
			        <div class="preview-table">
			          <el-table
			            :data="excelTableData"
			            border
			            height="500"
			            v-loading="loading"
			          >
			            <el-table-column
			              v-for="col in excelColumns"
			              :key="col.prop"
			              :prop="col.prop"
			              :label="col.label"
			              :width="col.width"
			              show-overflow-tooltip
			            ></el-table-column>
			          </el-table>
			        </div>
			
			        <!-- 分页区域 -->
			        <div class="pagination-footer">
			          <el-pagination
			            small
			            layout="prev, pager, next"
			            :total="excelTableData.length"
			            :page-size="pageSize"
			            @current-change="handlePageChange"
			          ></el-pagination>
			        </div>
			      </div>
			    </div>
			  </el-dialog>
		</div>
		<!-- Model -->
		<div class="model">
			<!-- 新增 v-if="showChild" @close="showChild = false" -->
			<div class="addModel">
				<!-- 在父组件的 template 部分 -->
				<addModel ref="addModel" :parent-method="loadData" @refresh="handleRefresh"></addModel>
			</div>
		</div>
	</div>
</template>

<script>
	// selfs / js
	// import MedicenCata from '@/external/MedicenCata.js'
	//  selfs / props
	import addModel from './Western/addDialogVisible.vue'
	import * as XLSX from 'xlsx';  // 修改这里，使用 * as 导入
	// 接口
	import { selectDrugCatalogue,getDrugList,deleteDrugP,importExcel }  from "@/api/systemCatalogue/MedicenCata.js";
	// others
	import { docclinic } from "@/api/cinic/cinic.js";
	
	export default {
		inject: ['reload'], // 无痕刷新
		components: {
			addModel
		},
		data() {
			return {
				defaultProps: {
					children: 'children',
					label: 'label'
				},
				// str
				toCode:'',
				treeValue:'', 
				tableHeight:'520', // table的高度，以便超出高度显示滚动条
				currentHeight:'', // 用于计算table的高度，以便超出高度显示滚动条
				windowWidth: '', //表格自适应宽度
				searchValue:'',
				CatalogueName:'西药目录',
				DropDownedName:'',
				iconComes:'el-icon-xy',
				// boolean
				loading:false,
				disabled:true,
				// showChild:false, // 控制子组件挂载
				// number
				ydNameId:0,
				pageNum: 1, //当前页currentPage
				pageSize: 20,
				totalSize: 20, //总条数
				pageSizeSave:0,
				// arr
				form: {},
				editform:{},
				res:[],
				NameOptions:[],
				restaurants: [], // 搜索关键字
				// title右侧按钮
				headerBtn:[
					{ refesh:"refesh", title:"查询", type:"", icon:"el-icon-Ssearch" },
					{ refesh:"refesh", title:"刷新", type:"", icon:"el-icon-refresh" },
					{ senior:"senior", title:"高级", type:"primary", icon:"" },
				],
				// 页面默认按钮// 基础按钮配置（始终显示）
				defaultButtons:[
					// { title:"新增西成药",icon:"el-icon-adds", type:"primary" },
					// { title:"修改西成药",icon:"el-icon-edit", type:"primary" },
					{ title:"查看",icon:"el-icon-watch", type:"primary" },
					{ title:"删除",icon:"el-icon-del", type:"danger" },
					// { title:"目录引用",icon:"el-icon-closeFiles", type:"primary" },
					// { title:"打印",icon:"el-icon-ggml", type:"primary" },
					{ title:"Excel表格导入",icon:"el-icon-export", type:"primary" },
					{ title:"关闭",icon:"el-icon-close", type:"primary" },
				],
				// 最终使用的按钮数组
				feetBtn: [],
				// tableRows
				tableRows:[
					{ name:"药品类型", prop:"drugTypeName" },
					{ name:"药品编码", prop:"code"},{ name:"药典名称", prop:"drugCodeName" },
					{ name:"药品名称", prop:"drugName"},{ name:"药品别名", prop:"alis"},
					{ name:"药品规格", prop:"drugSpec"},{ name:"包装规格", prop:"pacSpec" },
					{ name:"药品包装单位", prop:"pacUnt"},{ name:"包装数量", prop:"pacCnt" },
					{ name:"药品剂型", prop:"dosform" },{ name:"给药方式", prop:"ruteName" },{ name:"单位剂量", prop:"unitDose" },{ name:"剂量单位", prop:"dosUnt" },
					{ name:"生产厂家", prop:"manufacturerName"},
				],
				elTree:[
					{ label: '全部', path:'', title:'', icon:'el-icon-news',
						children:[
							{ id:1,label: '西药',path:'',title:'西药',icon:'el-icon-xy'},
							{ id:2,label: '中成药',path:'',title:'中成药',icon:'el-icon-zhongchengyao'},
						],
					},
				],
				tableData: [],
				docclinicOptions:[], // 获取诊所列表
				excelRawFile: null, // 保存上传的原始文件
				// exa
				TypeMap:{
					0: '否',
					1: '是',
					// ...待接口响应
				},
				expensiveTypeMap:{
					1: '普价',2: '贵重',
					3: '昂贵',4: '免费',
				},
				excelDialogVisible: false,  // 控制Excel导入对话框显示
				excelFileList: [],         // 上传的文件列表
				excelTableData: [],        // 解析后的Excel数据
				excelColumns: [],          // Excel表头
				uploadUrl: '/api/importExcel', // 模拟上传接口
				uploadHeaders: {
				  'Authorization': localStorage.getItem('token')
				},
				filePath:'',
				fileList:'',
				fileType: 'excel',
			};
		},
		watch: {
		    // 监听路由变化重新初始化按钮
		    '$route.path'(newPath) {
		      this.initButtons();
		    }
		},
		mounted() {
			// 数据源
			this.loadData();
			//获取动态盒子宽度，实时赋值给右侧 =i> this.$refs.mainRight.offsetWidth;
			this.$nextTick(()=>{
				this.updateWindowWidth();
				window.addEventListener('resize', this.updateWindowWidth);
				this.currentHeight = this.$getHeights();
				this.getTableHeight();
				this.initButtons(); // 引入全局自定义封装方法
			});
			this.getcilinc();
		},
		methods: {
			/*
				数据源
			*/
			async loadData(){
				let res = await getDrugList({
					drugName:this.searchValue,
					condis: this.treeValue,
					pageNum: this.pageNum,
					pageSize: this.pageSize
				})
				// this.reload();
				if(res.code === 200){
					this.loading = true;
					setTimeout(() =>{
						this.loading = true;//开始加载
						this.tableData = res.data.content;
						this.totalSize = res.data.totalSize;
						this.loading = false;
						this.restaurants = this.tableData;
						// 处理返回数据，添加 drugTypeName 字段
						this.tableData = res.data.content.map(item => {
							// 根据 drugType 值设置 drugTypeName
							let drugTypeName = '';
							if (item.drugType === 1) {
								drugTypeName = '西药';
							}
							// 返回新对象，包含原字段和新增的 drugTypeName
							return {
								...item,
								drugTypeName: drugTypeName
							};
						});
						// this.$message.success('数据已更新');
					},888)
				}
			},
			// 在methods部分添加刷新方法
			handleRefresh() {
			  this.loadData(); // 调用原有的数据加载方法
			},
			initButtons() {
			    // 获取当前路由路径
			    const currentPath = this.$route.path;
			    // 获取路由对应的权限按钮
			    const routeButtons = this.$getRouteButtons(currentPath);
			    // console.log(routeButtons,'routeButtonsrouteButtons');
			    // 合并到现有按钮数组
			    this.feetBtn = this.$mergeButtons(this.defaultButtons, routeButtons);
				// console.log(this.feetBtn,'this.feetBtnthis.feetBtn');
			},
			// props
			querySearch(queryString, cb) {
			    console.log(queryString,'queryString');
				// queryString = this.searchValue
				var restaurants = this.restaurants;
				var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
				clearTimeout(this.timeout);
				this.timeout = setTimeout(() => {
				  cb(results);
				}, 888 * Math.random());
			},
			createFilter(queryString) {
				return (restaurant) => {
				  console.log(restaurant);
				  return (restaurant.drugCodeName.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
				};
			},
			// 用于计算table的高度，以便超出高度显示滚动条
			getTableHeight(){
				let headerHeight = this.currentHeight.mainHeight
				let rightContentHeight = this.currentHeight.rightContentHeight
				let feetHeight = this.currentHeight.feetHeight
				let lastHeight = this.currentHeight.lastHeight
				this.tableHeight = this.currentHeight.rightContentHeight - feetHeight * 3
				// console.log(this.tableHeight,'this.tableHeightthis.tableHeight');
			},
			handleSelect(item) {
				this.searchValue = item.drugName
				this.loadData();
			},
			handleIconClick(ev) {
				this.loadData();
			},
			/*
				about tree
			*/
			async handleNodeClick(data){
				this.treeValue = data.id;
				this.loadData();
			},
			// 选择值
			handClickName(val){
				console.log(val);
			},
			async getcilinc(){
				// 所有菜单
				let res = await docclinic();
				this.docclinicOptions = res.data.map(v=>{ return { label: v.name , ...v }});
				// 将 民族 转换为 minZuMap 格式
				this.docclinicMap = this.docclinicOptions.reduce((map, item) => {
					map[item.id] = item.label;  // 使用 id 作为键，label 作为值
					return map;
				}, { 1: '数据不对，默认null' });  // 保留初始值
			},
			// edit
			// 编辑表格行数据
			editFormValue(row) {
			  if (!row || !row.id) {
			    this.$message.warning('请先选择一条要编辑的数据');
			    return;
			  }
			  
			  this.loading = true;
			  this.$refs.addModel.openAddModel({
			    id: row.id,
			    label: '修改西药目录',
			    isShow: true,
			    system: true,
			    mode: 'edit' // 新增mode参数区分新增和编辑
			  });
			  // 确保毒麻类型选项已加载
			    this.$nextTick(() => {
			      this.$refs.addModel.$refs.basicInfo.getDocVtByType();
			    });
			},
			handleDelete(rowId){
				console.log(rowId);
				this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
				  confirmButtonText: '确定',
				  cancelButtonText: '取消',
				  type: 'warning'
				}).then(async() => {
					let ress = await deleteDrugP({
						drugId: rowId
					})
					if(ress.code === 200){
						this.$message({type:'success',message:ress.message});
						this.loadData();
					}else{
						this.$message.error(ress.message)
					}
				}).catch(() => {
				  this.$message({
					type: 'info',
					message: '已取消删除'
				  });          
				});
			},
			
			// 编辑保存
			saveEditData(){
				
			},
			
			/*
				选择框
			*/

			/*
				about input
			*/

			/*
				about table
			*/
		    // col 里面包含了表头字段和名称，list 是表格数据
		    columnWidth(col, list) {
		         let prop = col.prop,lab = col.lab;
		         let width = 12; // 设定一个最小值
		         let maxlenStr = ""; // 最长字符串
		         for (let info of list) {
		           if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
		         }
		         width = Math.max(width, len(lab), len(maxlenStr));
		         // 表格自带的内边距(20px) 自调
		         return width + 12; // 这里加了 12px
		         function len(str) {
		           // 实际分配长度可根据需要自行调整
		           let length = 0;
		           for (const char of str + "") {
		             // 英文小写字符 8px
		             if ("a" <= char && char <= "z") length += 8;
		             // 英文大写字符 12px
		             else if ("A" <= char && char <= "Z") length += 8;
					 // 数字
					 else if (Number.isFinite(Number(char))) length += 8;
		             // 中文字符 12px
		             else if (char >= "\u4e00" && char <= "\u9fa5") length += 12;
		             // 其他 8px
		             else length += 8;
		           }
		           return length;
		         }
		    },
			// 表格行颜色等
			tableRowClassName({ row }) {
			  if (row.expensiveType === 3) {
			    return 'expensive-row';
			  }
			  return '';
			},
			// 新增等步骤
			handClick(i) {
				// i event
				switch (i) {
					case 0://
						// 处理索引0的逻辑 （刷新相当于搜索）
						this.loading = true;
						if(this.searchValue == ''){
							setTimeout(() => {
								this.$message.error('关键字不能为空！相当于搜索按钮');
								this.loading = false;		
							}, 1500)
						}else{
							this.loadData();
						}
					break;
					case 1:
						this.loading = true;
						setTimeout(() => {
							this.reload();
							this.$message({type:'success',message:'已刷新'})
							this.loading = false;		
						}, 1500)
					break;
					case 2:
						// 处理索引2的逻辑 高级选项
						// this.$message({ type: "info", message: "暂不支持,请联系工作人员!"});
					break;
				}
			},
			// 新增等步骤
			feetHandClick(v){
				// i event
				 if(v.title === '新增' || v.title.includes('新增')) {
				    this.$refs.addModel.openAddModel({
				      label: '新增',
				      isShow: true,
				      system: false
				    });
				  } 
				  else if (v.title === '修改西药目录' || v.title.includes('修改')) {
				      if (!this.currentTable) {
				        this.$message.warning("请先选择一条要编辑的数据");
				        return;
				      }
				      this.$refs.addModel.openAddModel({
				        id: this.currentTable.id,
				        label: '修改西药目录【Edit模式】',
				        isShow: true,
				        system: true,
				        mode: 'edit',
				      });
					  // 确保毒麻类型选项已加载
					    this.$nextTick(() => {
					      this.$refs.addModel.$refs.basicInfo.getDocVtByType();
					    });
				  }
				// 在 feetHandClick 方法中添加查看逻辑
				else if(v.title === '查看' || v.title.includes('查看')) {
				  if(!this.currentTable) {
				    this.$message.warning("请先选择一条要查看的数据");
				    return;
				  }
				   // 新增view模式
				  this.$refs.addModel.openAddModel({
				    id: this.currentTable.id,
				    label: '查看【Views模式】',
				    isShow: true,
				    system: true,
				    mode: 'view'
				  });
				}
				// 处理Excel导入
				else if (v.title === 'Excel表格导入' || v.title.includes('Excel')) {
				    this.handleExcelImport();
				}
				// 处理逻辑 => 删除
				else if(v.title == '删除' || v.title.includes('删除')){
					if(this.currentTable === undefined){
						this.$message({ type: "warning", message: "请先选择一条要删除的数据."});
					}else{
						console.log(this.currentTable.id);
						this.$confirm('此操作将永久删除该条药品数据, 是否继续?', '提示', {
						  confirmButtonText: '确定',
						  cancelButtonText: '取消',
						  type: 'warning'
						}).then(async() => {
							this.loading = true;
							setTimeout(async()=>{
								let ress = await deleteDrugP({
									drugId: this.currentTable.id
								})
								if(ress.code === 200){
									this.$message({type:'success',message:ress.message});
									this.loadData();
									this.loading = false;
								}else{
									this.$message.error(ress.message);
									this.loading = false;
								}
							},888)
						}).catch(() => {
						  this.$message({
							type: 'info',
							message: '已取消删除'
						  });          
						});
					
					}
				}
				// 处理逻辑 => 打印
				else if(v.title == '打印'){
					
				}
				// 处理逻辑 => 导出
				else if(v.title == '导出'){
					this.$confirm('敬请期待')
					.then(_ => {})
					.catch(_ => {});
				}
				// 处理逻辑 => 关闭
				else if(v.title == '关闭'){
					// 返回上一页
					  if (window.history.length > 1) {
						this.$router.go(-1);
					  } else {
						// 如果无历史记录则跳转首页
						this.$router.push('/');
					}
				}
			},
			// 打开Excel导入对话框
			handleExcelImport() {
			  this.excelDialogVisible = true;
			  this.resetImportData();
			},
			
			// 重置导入数据
			resetImportData() {
			  this.excelFileList = [];
			  this.excelTableData = [];
			  this.excelColumns = [];
			  this.fileList = [];
			  this.filePath = '';
			  this.currentPage = 1;
			},
			
			// 上传前校验
			beforeExcelUpload(file) {
			  const isExcel = file.type.includes('excel') || 
							 file.name.endsWith('.xlsx') || 
							 file.name.endsWith('.xls');
			  const isLt10M = file.size / 1024 / 1024 < 10;
		
			  if (!isExcel) {
				this.$message.error('只能上传Excel文件!');
				return false;
			  }
			  if (!isLt10M) {
				this.$message.error('文件大小不能超过10MB!');
				return false;
			  }
			  return true;
			},
			
			// 处理文件变化
			handleExcelChange(file, fileList) {
			    if (fileList.length > 1) {
			        this.excelFileList = [fileList[fileList.length - 1]];
			        return;
			    }
			    
			    this.excelFileList = fileList;
			    this.filePath = file.name;
			    this.excelRawFile = file.raw; // 保存原始文件对象
			    
			    // 更新文件列表
			    this.fileList = [{
			        name: file.name,
			        path: file.name,
			        status: '待处理'
			    }];
			    
			    // 读取Excel内容
			    this.readExcel(file.raw);
			},
			
			// 重新选择文件
			reSelectFile() {
			  this.resetImportData();
			},
			
			// 移除文件
			removeFile() {
			  this.resetImportData();
			},
			
			// 读取Excel文件
			readExcel(file) {
			  this.loading = true;
			  const reader = new FileReader();
			  
			  reader.onload = (e) => {
				try {
				  const data = new Uint8Array(e.target.result);
				  const workbook = XLSX.read(data, { type: 'array' });
				  
				  const firstSheetName = workbook.SheetNames[0];
				  const worksheet = workbook.Sheets[firstSheetName];
				  
				  const jsonData = XLSX.utils.sheet_to_json(worksheet);
				  
				  if (!jsonData || jsonData.length === 0) {
					this.$message.warning('Excel文件没有数据');
					return;
				  }
				  
				  // 处理表头
				  this.excelColumns = Object.keys(jsonData[0]).map(key => ({
					prop: key,
					label: key,
					width: 150
				  }));
				  
				  this.excelTableData = jsonData;
				  this.fileList[0].status = '导入成功';
				  
				  this.$message.success('Excel解析成功');
				} catch (error) {
				  console.error('Excel解析错误:', error);
				  this.fileList[0].status = '失败';
				  this.$message.error('Excel文件解析失败: ' + error.message);
				} finally {
				  this.loading = false;
				}
			  };
			  
			  reader.onerror = (error) => {
				console.error('文件读取错误:', error);
				this.fileList[0].status = '失败';
				this.$message.error('文件读取失败');
				this.loading = false;
			  };
			  
			  reader.readAsArrayBuffer(file);
			},
			
			// 提交Excel数据
			async submitExcel() {
			    if (!this.excelRawFile) {
			        this.$message.warning('请先上传Excel文件');
			        return;
			    }
			
			    this.loading = true;
			    
			    const formData = new FormData();
			    formData.append('file', this.excelRawFile);
			    
			    try {
			        const res = await importExcel(formData);
			        
			        if (res.code === 200) {
			            this.$message.success('导入成功');
			            this.excelDialogVisible = false;
			            this.loadData();
			        } else {
			            this.$message.error(res.message || '导入失败');
			        }
			    } catch (error) {
			        console.error('导入错误:', error);
			        // 从错误响应中获取真实Content-Type
			        const contentType = error.response?.headers?.['content-type'];
			        this.$message.error(`导入失败: ${contentType || '未知错误'}`);
			    } finally {
			        this.loading = false;
			    }
			},
			// 表格单选
			handleCurrentTableChange(val){
				console.log(val);
				this.currentTable = val
			},
			// db events 双击表格行
			handledbRow(row, column, event){
				if(row){
					this.loading = true;
					setTimeout(()=>{
						console.log(row,'双击过后查看');
						// 使用点语法
						// res.data.watch = true;
						let param = {
							id:row.id,
							label: '查看【Views模式】',
							isShow: true,
							system: true,
							mode: 'view'
						}
						this.loading = false;
						this.$refs.addModel.openAddModel(param);
					},888)
				} else { 
					this.$message({ type: "info", message: "未知异常，请稍后重试！"});
				}
			},
			handleClose(done) {
				this.$confirm('确认关闭？')
				  .then(_ => {
					this.formdisabled = true;
					location.reload();
					done();
				  })
				  .catch(_ => {
					this.formdisabled = this.formdisabled;
				  });
			},
			handleCommand(command) {
			  // 这里的 command 就是你点击的菜单项的 command 属性值
			  // console.log(command);
			  // 根据 command 值执行相应的逻辑
			  switch (command) {
				case 'a':
				  // 处理a的逻辑
				  console.log('执行A逻辑');
				  this.DropDownedName = '可用'
				  break;
				case 'b':
				  // 处理b的逻辑
				  console.log('执行B逻辑');
				  this.DropDownedName = '禁用'
				  break;
				case 'c':
				  // 处理b的逻辑
				  this.DropDownedName = '全部'
				  break;
				// ... 其他 case
			  }
			},
			// 拦截

			//分页
			//每页条数改变触发
			handleSizeChange(val) {
				console.log(`每页 ${val} 条`);
				this.pageNum = val;
				this.loadData();
			},
			//当前条数改变触发
			handleCurrentChange(val) {
				console.log(`当前页: ${val}`);
				this.pageNum = val;
				this.loadData();
			},
			// 实时宽度
			// 在updateWindowWidth方法中同步表格宽度
			updateWindowWidth() {
			  this.windowWidth = window.innerWidth - 288;
			  // 设置表格最小宽度
			  this.$nextTick(() => {
			    const table = document.querySelector('.el-table__body-wrapper');
			    if(table) table.style.minWidth = `${this.windowWidth}px`;
			  });
			},
			// 分页变化
			handlePageChange(val) {
			  this.currentPage = val;
			}
		}
	}
</script>

<style lang="less" scoped>
	/deep/ .el-table .expensive-row {
	  color: red;
	}
	
	/deep/ .el-table .expensive-row:hover > td {
	  background-color: rgba(255, 0, 0, 0.1) !important;
	}
	/deep/ .el-tabs--border-card>.el-tabs__content{
		padding: 8px;
	}
	.box {
	  height: calc(100vh - 108px); // 减去导航栏高度
	  width: 100%;
	  overflow: hidden;
		
		/deep/ .el-table {
	    width: 100%;
	    min-width: 100%;
	    background-color: transparent;
	    
	    // .el-table__body-wrapper {
	    //   overflow-x: auto;
	    //   overflow-y: auto;
	    // }
	    
	    &::before {
	      display: none;
	    }
	    
	    .el-table__empty-block {
	      background-color: transparent;
	    } 
	    /deep/ .el-table__header-wrapper {
	      overflow-x: scroll !important;
	      padding-bottom: 17px; /* 滚动条高度占位 */
	    }
		/* 小眼睛图标样式 */
		.el-icon-watch {
		  color: #409EFF;
		  &:hover {
		    color: #66b1ff;
		  }
		}
		.el-icon-shield {
		  color: #F56C6C;
		  &:hover {
		    color: #f78989;
		  }
		}
	}
	/deep/ .el-switch__label *{
		font-size: 12px;
	}
	/deep/ .el-table .cell{
		font-size: 12px;
		text-overflow: ellipsis;
		white-space: nowrap;
		overflow: hidden;
	}
	/deep/ .el-table th{
		font-size: 12px;
		background-color: #f1f1f1;
		border: none;
		color: #2d2d2d;
	}
	/deep/ .el-table {
	  width: 100% !important;
	  min-width: auto !important;
	  
	  .el-table__body-wrapper {
	    overflow-x: auto !important;
	    overflow-y: auto !important;
	  }
	  
	  .el-table__header-wrapper {
	    // overflow-x: scroll !important;
	    // padding-bottom: 17px !important; /* 为滚动条留出空间 */
	  }
	    
	    &::before {
	      display: none;
	    }
	    
	    .el-table__empty-block {
	      background-color: transparent;
	    }
	    // height: 100% !important;
	    .el-table__body-wrapper {
	      overflow-x: hidden;
	    }
	}
	/* 自定义高亮颜色 */
	::v-deep .el-table__body tr.current-row > td {
	  background-color: #00b3ff !important;
	  color: #f9f9f9; /* 可选：修改文字颜色 */
	}
	  .main {
	    display: flex;
	    height: 100%;
	    width: 100%;
	
	    // 左侧树形菜单
	    .main-left {
	      width: 128px;
	      height: 100%;
	      background: #f5f7fa;
	      border-right: 1px solid #e6e6e6;
	      overflow-y: auto;
	      scrollbar-width: none; /* Firefox */
	      -ms-overflow-style: none; /* IE 10+ */
	      
	      &::-webkit-scrollbar {
	        display: none; /* Chrome Safari */
	      }
	
	      /deep/ .el-tree {
	        height: 100%;
	        .el-tree-node__content {
	          height: 36px;
	        }
	      }
	    }
	    
	    // 右侧内容区域
	    .main-right {
	      flex: 1;
	      display: flex;
	      flex-direction: column;
	      height: 100%;
	      overflow: hidden;
	      
	      // 顶部搜索区域
		.main-icon {
			display: flex;
			align-items: center;
			padding: 12px;
			line-height: 40px;
			.main-icon-a{
				// width: 240px;
				// background-color: #00557f;
			}
			.main-icon-b{
				margin-left: 28px;
				/deep/ .el-dropdown{
					font-size: 12px;
					cursor: pointer;
				}
				/deep/ .el-dropdown:hover {
					font-weight: bold;
					color: #66b1ff;
				}
				/deep/ .el-icon--right{
					// background-color: #66b1ff;
				}
				/deep/ .el-popper[x-placement^=bottom]{
					margin-top: 0;
				}
			}
			// c
			.main-icon-c{
				display: flex;
				align-items: center;
				margin-left: 28px;
				/deep/ [data-v-2bacc09b] .el-color-picker__icon, .el-input[data-v-2bacc09b], .el-textarea[data-v-2bacc09b]{
					width: 80%;
				}
			}
		}
	      
	      // 表格容器（带滚动）
	      .table {
	        flex: 1;
			width: 100%;
	        overflow: hidden;
	        display: flex;
			opacity: .8;
	        flex-direction: column;
			/deep/ .el-pagination {
				margin: 12px;
			}
	    }
	      
	      // 底部固定区域
	      .feet {
	        height: 40px;
	        display: flex;
			align-items: center;
	        padding: 12px;
	        // background: #fff;
	        border-top: 1px solid #e6e6e6;
	        flex-shrink: 0;
	        
	        .feetBtn {
	          gap: 8px;
	        }
			
	        }
	    }
		
	  }
		.excel{
			display: flex;
			align-items: center;
			justify-content: center;
			/deep/ .el-dialog__header{
				padding: 4px;
				background-color: #007bb0;
			}
			/deep/ .el-dialog__title{
				color: #fff;
				font-size: 12px;
			}
			/deep/ .el-dialog__headerbtn{
				top: 10px;
			}
			/deep/ .el-dialog__body{
				padding: 10px;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close{
				color: #fff;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close:hover{
				background-color: brown;
			}
			/deep/ .el-table .cell{
				font-size: 12px;
				font-weight: 400;
				color: #0c0c0c;
				text-align: left;
			}
			
			/* Excel导入样式 */
			.excel-import-dialog {
			  .el-dialog__body {
				padding: 10px 20px;
			  }
			}
			
			.excel-import-container {
			  display: flex;
			  height: 600px;
			  
			  .left-panel {
				flex: 1;
				display: flex;
				flex-direction: column;
				padding-right: 15px;
				border-right: 1px solid #ebeef5;
				
				.upload-header {
				  padding: 10px 0;
				  
				  .upload-demo {
					text-align: center;
				  }
				}
				
				.file-info {
				  flex: 1;
				  display: flex;
				  flex-direction: column;
				  
				  .file-type-select {
					padding: 10px 0;
					
					.el-form-item {
					  margin-bottom: 10px;
					}
				  }
				  
				  .file-table {
					flex: 1;
					overflow: hidden;
				  }
				}
				
				.action-footer {
				  padding: 10px 0;
				  text-align: center;
				  
				  .el-button {
					width: 100%;
				  }
				}
			  }
			  
			  .right-panel {
				flex: 2;
				display: flex;
				flex-direction: column;
				padding-left: 15px;
				overflow: hidden; /* 防止整体溢出 */
				.preview-header {
				  padding: 10px 0;
				  border-bottom: 1px solid #ebeef5;
				  
				  h4 {
					margin: 0;
					font-size: 14px;
					color: #606266;
				  }
				}
				
				.preview-table {
				  flex: 1;
				  width: 100%;
				  overflow: hidden;
				}
				
				.pagination-footer {
				  padding: 10px 0;
				  text-align: center;
				  border-top: 1px solid #ebeef5;
				}
			  }
			}
			
			.el-upload-dragger {
			  width: 100%;
			  padding: 20px;
			}
			
			.el-upload__tip {
			  font-size: 12px;
			  color: #909399;
			  margin-top: 5px;
			}
		}
		.addModel{
			/deep/ .el-dialog__header{
				padding: 4px;
				background-color: #007bb0;
			}
			/deep/ .el-dialog__title{
				color: #fff;
				font-size: 12px;
			}
			/deep/ .el-dialog__body{
				padding: 8px;
			}
			/deep/ .el-select-dropdown__item {
				font-size: 12px;
			}
			

			// /deep/ .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
			// 	margin-bottom: 12px;
			// }
		}
		.editModel{
			/deep/ .el-dialog__header{
				padding: 4px;
				background-color: #007bb0;
			}
			/deep/ .el-dialog__title{
				color: #fff;
				font-size: 12px;
			}
			/deep/ .el-dialog__body{
				padding: 8px;
			}
			/deep/ .el-select-dropdown__item {
				font-size: 12px;
			}
		}
	}

</style>